//按钮监听
import { onMounted, onUnmounted } from 'vue';
// useKeydown(['ArrowRight', 'ArrowLeft'], (event: any) => {
//   event.preventDefault();
//   switch (event.key) {
//     case 'ArrowLeft':
//       drawer.value = true;
//       break;
//   }
// });
export const useKeydown = (keys: string | string[], callback: (event: KeyboardEvent) => void) => {
  // 如果 keys 是字符串，则转换为数组
  const targetKeys = Array.isArray(keys) ? keys : [keys];
  // 定义处理按键事件的方法
  const handleKeydown = (event: KeyboardEvent) => {
    if (targetKeys.includes(event.key)) {
      callback(event);
    }
  };

  // 在组件挂载时添加事件监听器
  onMounted(() => {
    window.addEventListener('keydown', handleKeydown);
  });

  // 在组件卸载时移除事件监听器以避免内存泄漏
  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeydown);
  });
};
// useCombinationKeys({ keys: ['ArrowRight', 'ArrowLeft'], modifiers: ['ctrl'] }, (event: any) => {
//   event.preventDefault();
//   switch (event.key) {
//     case 'ArrowLeft':
//       drawer.value = true;
//       break;
//   }
// });
export const useCombinationKeys = (keyCombinations: { keys: string[]; modifiers: ('ctrl' | 'shift' | 'alt' | 'meta')[] }, callback: (event: KeyboardEvent) => void) => {
  const handleKeydown = (event: KeyboardEvent) => {
    const isCorrectKey = keyCombinations.keys.includes(event.key);
    const modifierKeysMatch = keyCombinations.modifiers.every((modifier) => ({ ctrl: event.ctrlKey, shift: event.shiftKey, alt: event.altKey, meta: event.metaKey })[modifier]);

    if (isCorrectKey && modifierKeysMatch) {
      callback(event);
    }
  };

  onMounted(() => {
    window.addEventListener('keydown', handleKeydown);
  });

  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeydown);
  });
};
